package com.jweb.framework.http.ajax;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jweb.framework.core.ContextEx;
import com.jweb.framework.core.CoreException;
import com.jweb.framework.core.channel.ChannelContext;
import com.jweb.framework.core.channel.ChannelInterceptor;
import com.jweb.framework.core.channel.interceptors.ExceptionHandler;


public class AjaxResponseInterceptor<Request, Response> implements ChannelInterceptor<Request, Response> {
	
	private String encoding = "UTF8" ;
	
	private ExceptionHandler exceptionHandler ;
	
	public void setExceptionHandler(ExceptionHandler exceptionHandler){
		this.exceptionHandler = exceptionHandler ;
	}
	
	public void setEncoding(String s){
		if("UTF-8".equals(s)){
			s = "UTF8";
		}
		else if("UTF-16BE".equals(s)){
			s = "UTF16_BE";
		}
		else if("UTF-16LE".equals(s)){
			s = "UTF16_LE";
		}
		else if("UTF-32BE".equals(s)){
			s = "UTF32_BE";
		}
		else if("UTF-32LE".equals(s)){
			s = "UTF32_LE";
		}
		else {
			throw new IllegalArgumentException("unsupported encoding , support:UTF-8 , UTF-16BE , UTF-16LE , UTF-32BE , UTF-32LE . ");
		}
		this.encoding = s ;
	}

	@Override
	public void onRequest(ChannelContext<Request, Response> channelContext,
			ContextEx ctxEx) throws CoreException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(ChannelContext<Request, Response> channelContext,
			ContextEx ctxEx, Throwable throwable) {
		
		byte[] ajaxResp = null ;
		if((throwable != null) && (this.exceptionHandler != null)){
			this.exceptionHandler.handleException(throwable , ctxEx);
			ajaxResp = JSON.toJSONBytes(ctxEx.getDataMap() , SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullNumberAsZero);
			channelContext.setResponsePayload(ajaxResp);
			return ;
		}
		
		
		if(!ctxEx.getDataMap().isEmpty()){
			if(ctxEx.getData("outputStream") instanceof byte[]){
				
			}
			else {
				ajaxResp = JSON.toJSONBytes(ctxEx.getDataMap() , SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullNumberAsZero);
				channelContext.setResponsePayload(ajaxResp);
			}
		}
		
	}

}
